package com.demo.web;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = {"/*"})
public class LoginFilter implements Filter {
    //String[]此处的url路径需要登录后，才有权访问
    String[] excludeUrls = new String[]{"/code/index.html","/code/StudentServlet"};//

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        // 类型向下转型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        HttpSession session = request.getSession();
        String uri = request.getRequestURI();
        boolean pass = false;
        if (excludeUrls != null) {
            for (String url : excludeUrls) {
                if (uri.indexOf(url) > -1) {
                    pass = true;
                    break;
                }
            }
        }
        if (!pass) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //如果有权限就直接登录
            if (session.getAttribute("userKey_session") != null) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                String requestType = request.getHeader("X-Requested-With");
                //判断是否是ajax请求
                if (requestType != null && "XMLHttpRequest".equals(requestType)) {
                    response.getWriter().write("当前用户未登录");
                } else {
                    response.sendRedirect("/code/login.html");
                }
                return;
            }
        }

    }

    @Override
    public void destroy() {

    }
}
